<template>
  <view class="container">
    <!-- Form Header -->
    <view class="form-header">
      <text class="header-title">{{ isEditing ? 'Edit Event' : 'New Event' }}</text>
    </view>

    <!-- Event Form -->
    <scroll-view scroll-y class="form-content">
      <!-- Title -->
      <view class="form-group">
        <text class="form-label">Title</text>
        <u-input
          v-model="event.title"
          placeholder="Enter event title"
          :border="true"
        ></u-input>
      </view>

      <!-- Date & Time -->
      <view class="form-group">
        <text class="form-label">Date & Time</text>
        <view class="datetime-inputs">
          <view class="date-picker">
            <u-input
              v-model="formattedDate"
              placeholder="Select date"
              :disabled="true"
              :border="true"
              @click="showDatePicker = true"
            >
              <template #suffix>
                <u-icon name="calendar" size="28" color="#666"></u-icon>
              </template>
            </u-input>
          </view>
          <view class="time-picker">
            <u-input
              v-model="formattedTime"
              placeholder="Select time"
              :disabled="true"
              :border="true"
              @click="showTimePicker = true"
            >
              <template #suffix>
                <u-icon name="clock" size="28" color="#666"></u-icon>
              </template>
            </u-input>
          </view>
        </view>
      </view>

      <!-- Duration -->
      <view class="form-group">
        <text class="form-label">Duration</text>
        <u-number-box
          v-model="event.duration"
          :min="1"
          :max="8"
          :step="0.5"
          :inputWidth="120"
        ></u-number-box>
        <text class="duration-unit">hours</text>
      </view>

      <!-- Location -->
      <view class="form-group">
        <text class="form-label">Location</text>
        <u-input
          v-model="event.location"
          placeholder="Enter location"
          :border="true"
        ></u-input>
      </view>

      <!-- Description -->
      <view class="form-group">
        <text class="form-label">Description</text>
        <u-textarea
          v-model="event.description"
          placeholder="Enter event description"
          :height="200"
        ></u-textarea>
      </view>

      <!-- Color -->
      <view class="form-group">
        <text class="form-label">Color</text>
        <view class="color-picker">
          <view 
            v-for="(color, index) in eventColors"
            :key="index"
            :class="['color-option', { selected: event.color === color }]"
            :style="{ backgroundColor: color }"
            @click="event.color = color"
          ></view>
        </view>
      </view>

      <!-- Reminder -->
      <view class="form-group">
        <text class="form-label">Reminder</text>
        <u-dropdown>
          <u-dropdown-item
            v-model="event.reminder"
            :title="getReminderText"
            :options="reminderOptions"
          ></u-dropdown-item>
        </u-dropdown>
      </view>

      <!-- Repeat -->
      <view class="form-group">
        <text class="form-label">Repeat</text>
        <u-dropdown>
          <u-dropdown-item
            v-model="event.repeat"
            :title="getRepeatText"
            :options="repeatOptions"
          ></u-dropdown-item>
        </u-dropdown>
      </view>
    </scroll-view>

    <!-- Action Buttons -->
    <view class="action-buttons">
      <u-button 
        :plain="true"
        @click="cancel"
      >Cancel</u-button>
      <u-button
        type="primary"
        :disabled="!isValid"
        @click="saveEvent"
      >{{ isEditing ? 'Update' : 'Create' }}</u-button>
    </view>

    <!-- Date Picker -->
    <u-calendar
      :show="showDatePicker"
      :mode="'date'"
      :minDate="minDate"
      :maxDate="maxDate"
      @close="showDatePicker = false"
      @change="handleDateChange"
    ></u-calendar>

    <!-- Time Picker -->
    <u-picker
      :show="showTimePicker"
      :columns="[hours, minutes]"
      @close="showTimePicker = false"
      @confirm="handleTimeChange"
    ></u-picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isEditing: false,
      showDatePicker: false,
      showTimePicker: false,
      event: {
        title: '',
        date: new Date().toISOString().split('T')[0],
        startTime: '09:00',
        duration: 1,
        location: '',
        description: '',
        color: '#4b7bec',
        reminder: 15,
        repeat: 'none'
      },
      eventColors: [
        '#4b7bec',  // Blue
        '#2ed573',  // Green
        '#ff4757',  // Red
        '#ffa502',  // Orange
        '#2f3542',  // Dark
        '#a4b0be'   // Gray
      ],
      reminderOptions: [
        { label: 'None', value: 0 },
        { label: '15 minutes before', value: 15 },
        { label: '30 minutes before', value: 30 },
        { label: '1 hour before', value: 60 },
        { label: '2 hours before', value: 120 },
        { label: '1 day before', value: 1440 }
      ],
      repeatOptions: [
        { label: 'Never', value: 'none' },
        { label: 'Every day', value: 'daily' },
        { label: 'Every week', value: 'weekly' },
        { label: 'Every month', value: 'monthly' }
      ],
      hours: Array.from({ length: 24 }, (_, i) => ({
        text: i.toString().padStart(2, '0'),
        value: i
      })),
      minutes: Array.from({ length: 12 }, (_, i) => ({
        text: (i * 5).toString().padStart(2, '0'),
        value: i * 5
      }))
    }
  },
  computed: {
    minDate() {
      return new Date().getTime()
    },
    maxDate() {
      const date = new Date()
      date.setFullYear(date.getFullYear() + 1)
      return date.getTime()
    },
    formattedDate() {
      return new Date(this.event.date).toLocaleDateString('en-US', {
        weekday: 'short',
        month: 'short',
        day: 'numeric',
        year: 'numeric'
      })
    },
    formattedTime() {
      return this.event.startTime
    },
    getReminderText() {
      const option = this.reminderOptions.find(o => o.value === this.event.reminder)
      return option ? option.label : 'None'
    },
    getRepeatText() {
      const option = this.repeatOptions.find(o => o.value === this.event.repeat)
      return option ? option.label : 'Never'
    },
    isValid() {
      return (
        this.event.title.trim() &&
        this.event.date &&
        this.event.startTime
      )
    }
  },
  onLoad(options) {
    if (options.id) {
      this.isEditing = true
      // TODO: Fetch event data
      // this.event = { ...fetchedEvent }
    }
  },
  methods: {
    handleDateChange(e) {
      this.showDatePicker = false
      this.event.date = new Date(e.timestamp).toISOString().split('T')[0]
    },
    handleTimeChange(e) {
      this.showTimePicker = false
      const [hour, minute] = e.value
      this.event.startTime = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
    },
    cancel() {
      uni.navigateBack()
    },
    async saveEvent() {
      if (!this.isValid) return

      uni.showLoading({
        title: this.isEditing ? 'Updating...' : 'Creating...'
      })

      try {
        // TODO: Implement event saving/updating
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        uni.hideLoading()
        uni.showToast({
          title: this.isEditing ? 'Event updated' : 'Event created',
          icon: 'success'
        })
        
        uni.navigateBack()
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: 'Failed to save event',
          icon: 'error'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.form-header {
  background-color: #ffffff;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.form-content {
  flex: 1;
  padding: 30rpx;

  .form-group {
    background-color: #ffffff;
    padding: 30rpx;
    border-radius: 12rpx;
    margin-bottom: 30rpx;

    .form-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
      display: block;
    }

    .datetime-inputs {
      display: flex;
      gap: 20rpx;

      .date-picker, .time-picker {
        flex: 1;
      }
    }

    .duration-unit {
      font-size: 28rpx;
      color: #666;
      margin-left: 20rpx;
    }

    .color-picker {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;

      .color-option {
        width: 80rpx;
        height: 80rpx;
        border-radius: 40rpx;
        cursor: pointer;

        &.selected {
          transform: scale(1.1);
          box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
        }
      }
    }
  }
}

.action-buttons {
  padding: 30rpx;
  display: flex;
  gap: 20rpx;
  background-color: #ffffff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  :deep(.u-button) {
    flex: 1;
  }
}
</style> 